<template>
  <div class="saved-plan-wrapper" v-if="list.length > 0">
    <div class="header-wrapper flex-between mt10 mb10">
      <h4>已保存{{($route.meta.title+"").substring(0,2)}}内容</h4>
      <Poptip confirm title="确定删除选中的数据吗?" @on-ok="batchDelete">
        <Button
          type="error"
          size="small"
          :disabled="selectList.length <= 0"
          >删除</Button
        >
      </Poptip>
    </div>
    <Form
      ref="planValidate"
      :model="planValidate"
      :rules="ruleValidate"
      :label-width="0"
    >
      <TableList
        :data="list"
        :total="total"
        :showDef="false"
        :page="query.pageIndex"
        :size="query.pageSize"
        :columns="planCol"
        selectKey="classNumberId"
        ref="selectTable"
        :selection.sync="selectList"
        @queryFun="queryTeachSchedule"
      ></TableList>
    </Form>
  </div>
</template>
<script>
import moment from 'moment';
import {
    queryTeachSchedule,
    updateTeachSchedule,
    deleteTeachSchedule
} from '@/api/selfStudy/class_new.js';
import typeMixin from '../mixins/typeMixin';
import { showTimeNotSecond } from '@/libs/utils';
export default {
    name: 'SavePlanList',
    props: {
        id: {
            type: String,
            default: ''
        }
    },
    mixins: [typeMixin],
    data() {
        const validateTime = (rule, value, callback, row) => {
            //验证警戒值
            let _this = this;
            // let length = _this.planValidate.planList.length;
            // let preEnd = row._index > 0 ? _this.planValidate.planList[row._index - 1] : '';
            // let nextStart =
            //     row._index < length - 1 ? _this.planValidate.planList[row._index + 1] : '';
            if (value.length != 2 || !value) {
                _this.planValidate.planList[row._index].timeTip = row.timeTip = '时间不能为空';
                console.log('时间不能为空');
                callback(new Error('时间不能为空'));
            } else if (value.length > 0) {
                let startTime = new Date(value[0]).getTime();
                let endTime = new Date(value[1]).getTime();
                if (startTime < new Date().getTime()) {
                    _this.planValidate.planList[row._index].timeTip = row.timeTip =
                        '开始时间不能小于当前时间';
                    callback(new Error('开始时间不能小于当前时间'));
                } else if (startTime === endTime) {
                    _this.planValidate.planList[row._index].timeTip = row.timeTip =
                        '结束时间不能等于开始时间';
                    callback(new Error('结束时间不能等于开始时间'));
                } else {
                    callback();
                }
                // else if (preEnd && startTime < new Date(preEnd.time[1]).getTime()) {
                //     _this.planValidate.planList[row._index].timeTip = row.timeTip = '培训时间冲突';
                //     callback(new Error('培训时间冲突'));
                // } else if (nextStart && endTime > new Date(nextStart).getTime()) {
                //     _this.planValidate.planList[row._index].timeTip = row.timeTip = '培训时间冲突';
                //     callback(new Error('培训时间冲突'));
                // } else {
                //     _this.planValidate.planList[row._index].timeTip = row.timeTip = '';
                //     callback();
                // }
            } else {
                _this.planValidate.planList[row._index].timeTip = row.timeTip = '';
                callback();
            }
        };
        return {
            query: {
                pageIndex: 1,
                pageSize: 10,
                egId: this.id
            },
            list: [],
            planValidate: {
                planList: []
            },
            ruleValidate: {},
            selectList: [],
            total: 0,
            pickerOptions: {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            },
            planCol: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'left'
                },
                { title: '名称', key: 'name', minWidth: 100, tooltip: true },
                {
                    title: '状态',
                    key: 'cnStatus',
                    minWidth: 100,
                    tooltip: true,
                    setColor: (cnStatus) => {
                        return this.filterStatus(cnStatus, 'color');
                    },
                    filter: (cnStatus) => {
                        return this.filterStatus(cnStatus, 'text');
                    }
                },
                {
                    title: (this.$route.meta.title+"").substring(0,2) + '类型',
                    key: 'egType',
                    width: 100,
                    filter: (egType) => {
                        return egType === 'exam' ? '考试' : '课件';
                    }
                },
                {
                    title: (this.$route.meta.title+"").substring(0,2) + '形式',
                    key: 'type',
                    width: 120,
                    render: (h, params) => {
                        let optionArr = params.row.typeList.map((item) => {
                            return h(
                                'Option',
                                {
                                    props: {
                                        value: item.key
                                    }
                                },
                                item.title
                            );
                        });
                        if (optionArr.length > 1 && params.row.edit) {
                            return h(
                                'FormItem',
                                {
                                    props: {
                                        'label-width': 0,
                                        rules: {
                                            type: 'number',
                                            required: true,
                                            message: '不能为空',
                                            trigger: 'change'
                                        },
                                        // showMessage: false,
                                        prop: 'planList.' + params.index + '.type'
                                    },
                                    style: {
                                        margin: 0,
                                        width:'100%'
                                    },
                                    ref: `type-${params.index}`
                                },
                                [
                                    h(
                                        'Select',
                                        {
                                            props: {
                                                transfer: true,
                                                placeholder: '请选择',
                                                value: params.row.type
                                            },
                                            on: {
                                                'on-change': (type) => {
                                                    params.row.type = this.planValidate.planList[
                                                        params.index
                                                    ].type = type;
                                                    // this.formData.planList[params.index].type = type;
                                                    this.planValidate.planList[
                                                        params.index
                                                    ].classTypeList = params.row.classTypeList = this.classTypeList.filter(
                                                        (item) => item.type === type
                                                    );
                                                    if (params.row.classTypeList.length === 1) {
                                                        params.row.classType = this.planValidate.planList[
                                                            params.index
                                                        ].classType =
                                                            params.row.classTypeList[0].key;
                                                    } else if (
                                                        params.row.classTypeList.length === 0
                                                    ) {
                                                        params.row.classType = this.planValidate.planList[
                                                            params.index
                                                        ].classType = '';
                                                    }
                                                }
                                            }
                                        },
                                        optionArr
                                    )
                                ]
                            );
                        } else {
                            return h('span', this.filterType(params.row.type));
                        }
                    }
                },
                {
                    title: '上课模式',
                    key: 'classType',
                    width: 120,
                    render: (h, params) => {
                        if (!params.row.classTypeList) {
                            return h('span', '-');
                        }
                        let optionArr = params.row.classTypeList.map((item) => {
                            return h(
                                'Option',
                                {
                                    props: {
                                        value: item.key
                                    }
                                },
                                item.title
                            );
                        });
                        if (optionArr.length > 0 && params.row.edit) {
                            return h(
                                'FormItem',
                                {
                                    props: {
                                        'label-width': 0,
                                        rules: {
                                            type: 'string',
                                            required: true,
                                            message: '不能为空',
                                            trigger: 'change'
                                        },
                                        // showMessage: false,
                                        prop: 'planList.' + params.index + '.classType'
                                    },
                                    style: {
                                        margin: 0,
                                        width:'100%'
                                    },
                                    ref: `classType-${params.index}`
                                },
                                [
                                    h(
                                        'Select',
                                        {
                                            props: {
                                                transfer: true,
                                                placeholder: '请选择',
                                                value: params.row.classType
                                            },
                                            on: {
                                                'on-change': (classType) => {
                                                    params.row.classType = this.planValidate.planList[
                                                        params.index
                                                    ].classType = classType;
                                                }
                                            }
                                        },
                                        optionArr
                                    )
                                ]
                            );
                        } else {
                            return h('span', this.filterClassType(params.row.classType));
                        }
                    }
                },
                {
                    title: '培训时间',
                    key: 'time',
                    minWidth: 300,
                    render: (h, params) => {
                        if (params.row.edit) {
                            return h(
                                'FormItem',
                                {
                                    props: {
                                        'label-width': 0,
                                        rules: {
                                            type: 'array',
                                            // required: true,
                                            // message: '时间不能为空',
                                            trigger: 'blur',
                                            validator: (rule, value, callback) => {
                                                return validateTime(
                                                    rule,
                                                    params.row.time,
                                                    callback,
                                                    params.row
                                                );
                                            }
                                        },
                                        // showMessage: false,
                                        // this.planValidate.planList
                                        prop: 'planList.' + params.index + '.time'
                                    },
                                    attrs: {
                                        title: params.row.timeTip
                                    },
                                    style: {
                                        margin: 0,
                                        width:'100%'
                                    },
                                    key: params.row.id,
                                    ref: `time-${params.index}`
                                },
                                [
                                    h('DatePicker', {
                                        key: params.row.id,
                                        props: {
                                            confirm: true,
                                            value: params.row.time,
                                            type: 'datetimerange',
                                            format: 'yyyy-MM-dd HH:mm',
                                            placeholder: '请选择时间',
                                            options: {
                                                disabledDate(date) {
                                                    return (
                                                        date &&
                                                        date.valueOf() < Date.now() - 86400000
                                                    );
                                                }
                                            },
                                            transfer: true
                                        },
                                        ref: `datepicker-${params.index}`,
                                        style: {
                                            width: '100%'
                                        },
                                        on: {
                                            'on-change': (time) => {
                                                params.row.selectTime = time;
                                                if (
                                                    time &&
                                                    time.length === 2 &&
                                                    new Date(time[0]).getTime() <
                                                        new Date().getTime()
                                                ) {
                                                    params.row.selectTime[0] = moment(
                                                        new Date().getTime() + 3 * 60 * 1000
                                                    ).format('YYYY-MM-DD HH:mm');
                                                }
                                                if (
                                                    time &&
                                                    time.length === 2 &&
                                                    new Date(time[1]).getTime() <
                                                        new Date().getTime()
                                                ) {
                                                    params.row.selectTime[1] = moment(
                                                        new Date().getTime() + 5 * 60 * 1000
                                                    ).format('YYYY-MM-DD HH:mm');
                                                }
                                            },
                                            'on-ok': (time) => {
                                                params.row.isClickOkBtn = this.planValidate.planList[
                                                    params.index
                                                ].isClickOkBtn = true;
                                                this.curModPlan = params.row;
                                                params.row.time = this.planValidate.planList[
                                                    params.index
                                                ].time = params.row.selectTime;
                                                this.planValidate.planList.sort((a, b) => {
                                                    if (
                                                        a.time.length === 2 &&
                                                        b.time.length === 2
                                                    ) {
                                                        return (
                                                            new Date(a.time[0]).getTime() -
                                                            new Date(b.time[0]).getTime()
                                                        );
                                                    } else if (
                                                        b.time.length === 2 &&
                                                        (!a.time || a.time.length === 0)
                                                    ) {
                                                        return 1;
                                                    }
                                                });
                                                this.planValidate.planList.forEach(
                                                    (plan, index) => {
                                                        if (plan.time.lenght === 2) {
                                                            this.$refs[
                                                                'planValidate'
                                                            ].validateField(
                                                                'planList.' + index + '.time'
                                                            );
                                                        }
                                                    }
                                                );
                                            },
                                            'on-clear': () => {
                                                params.row.time = this.planValidate.planList[
                                                    params.index
                                                ].time = [];
                                            },
                                            'on-open-change': (isOpen) => {
                                                this.$nextTick(() => {
                                                    if (isOpen) {
                                                        // 显示组件
                                                        params.row.isClickOkBtn = this.planValidate.planList[
                                                            params.index
                                                        ].isClickOkBtn = false;
                                                        params.row.originalTime = this.planValidate.planList[
                                                            params.index
                                                        ].originalTime = params.row.time;
                                                    } else {
                                                        // 隐藏操作
                                                        if (!params.row.isClickOkBtn) {
                                                            // 不是通过点击确认按钮关闭DatePicker组件时，复原时间
                                                            params.row.time = this.planValidate.planList[
                                                                params.index
                                                            ].time = params.row.originalTime;
                                                            if (
                                                                !params.row.originalTime ||
                                                                params.row.originalTime.length === 0
                                                            ) {
                                                                this.$refs['selectTable'].$refs[
                                                                    `datepicker-${params.index}`
                                                                ].handleClear();
                                                            }
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    })
                                ]
                            );
                        } else {
                            return h(
                                'span',
                                params.row.time.length === 2
                                    ? `${showTimeNotSecond(params.row.time[0])} ~ ${showTimeNotSecond(params.row.time[1])}`
                                    : '-'
                            );
                        }
                    }
                },
                {
                    title: '操作',
                    width: 120,
                    slot: 'action',
                    opList: [
                        {
                            txt: '修改',
                            show: (data) => {
                                return data.edit === false;
                            },
                            fun: (data) => {
                                data.edit = true;
                                this.planValidate.planList[data._index].edit = true;
                            },
                            disabled: (data) => {
                                return data.cnStatus !== 0;
                            }
                        },
                        {
                            txt: '保存',
                            show: (data) => {
                                return data.edit === true;
                            },
                            fun: (data) => {
                                this.updateTeachSchedule(data, data._index);
                            }
                        },
                        {
                            txt: '删除',
                            type: 'delete',
                            tooltip: true,
                            title: '确定删除吗？',
                            disabled: (data) => {
                                return data.cnStatus !== 0;
                            },
                            fun: (data) => {
                                return this.deleteTeachSchedule([data.classNumberId]);
                            }
                        }
                    ]
                }
            ]
        };
    },
    mounted() {
        if (!this.id) {
            return;
        }
        this.queryTeachSchedule();
    },
    methods: {
        getOptions() {
            return {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            };
        },
        queryTeachSchedule() {
            queryTeachSchedule(this.query)
                .then(({ code, attribute: data, message }) => {
                    if (code === 1) {
                        let list = data.dataList;
                        list.forEach((planItem) => {
                            planItem.time = [planItem.startTime, planItem.endTime];
                            planItem.edit = false;
                            if (planItem.egType === 'exp' && planItem.expType !== 0) {
                                //非实操课件只能作为作业
                                planItem.type = 1;
                            } else if (planItem.egType === 'exam') {
                                planItem.type = 2;
                            }
                            planItem.typeList = this.typeList.filter((item) => {
                                return (
                                    item.egType === planItem.egType &&
                                    (planItem.expType
                                        ? item.optionalExpType.includes(planItem.expType)
                                        : true)
                                );
                            });
                            planItem.classTypeList = this.classTypeList.filter(
                                (item) => item.type === planItem.type
                            );
                            planItem._disabled = planItem.cnStatus !== 0;
                        });
                        this.list = data.dataList;
                        this.planValidate.planList = data.dataList;
                        this.total = data.totalCount;
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {});
        },
        changePage(page) {
            this.query.pageIndex = page;
            this.queryTeachSchedule();
        },
        // 编辑课节
        async updateTeachSchedule(plan, index) {
            let fields = [
                'planList.' + index + '.type',
                'planList.' + index + '.classType',
                'planList.' + index + '.time'
            ];
            let _this = this;
            if (plan.type === 1) {
                //作业
                fields = ['planList.' + index + '.type', 'planList.' + index + '.time'];
            } else if (plan.type === 2) {
                //考试
                fields = ['planList.' + index + '.time'];
            }
            let validResults = await Promise.all(
                fields.map((item) => {
                    let p = new Promise(function(resolve, reject) {
                        if (plan.type === 1) {
                            //作业
                            resolve();
                        } else {
                            _this.$refs['planValidate'].validateField(item, (error) => {
                                resolve(error);
                            });
                        }
                    });
                    return p;
                })
            );
            if (validResults.some((error) => error)) {
                return;
            }
            let { classNumberId, classType, cnStatus, createTime, egType, exId, name, type } = plan;
            let params = {
                classNumberId,
                classType,
                cnStatus,
                createTime,
                egType,
                exId,
                name,
                egId: this.id,
                type,
                endTime: `${plan.time[1]}:00`,
                startTime: `${plan.time[0]}:00`
            };
            updateTeachSchedule(params)
                .then(({ code, attribute: data, message }) => {
                    if (code === 1) {
                        this.$Message.info('保存成功');
                        plan.edit = false;
                        this.planValidate.planList[index].edit = false;
                        this.queryTeachSchedule();
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {});
        },
        // 删除课节
        deleteTeachSchedule(ids) {
            deleteTeachSchedule(ids)
                .then(({ code, attribute: data, message }) => {
                    if (code === 1) {
                        this.clearSelect()
                        this.queryTeachSchedule();
                        this.$Message.info(message);
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {});
        },
        batchDelete() {
            if (this.selectList.length === 0) {
                this.$Message.info('请选择要删除数据');
                return;
            }
            let ids = this.selectList.map((item) => item.classNumberId);
            this.deleteTeachSchedule(ids);
        },
        dealTime(time) {
            return time.substring(0, time.length - 3);
        },
        // selectData(selection) {
        //     this.selectList = selection;
        // },
        handleClose(item) {
            this.$refs.selectTable.closeItem(item);
        },
        clearSelect() {
            this.$refs.selectTable.clearSelect();
        }
    }
};
</script>
<style scoped>
.flex-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex {
  display: flex;
  align-items: center;
}
.mr10 {
  margin-right: 10px;
}
.mt10 {
  margin-top: 10px;
}
.mr10 {
  margin-right: 10px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
